﻿using DevExpress.Utils;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WinForm_Mes
{
    public partial class LargeScreenDisplayForm : DevExpress.XtraEditors.XtraForm
    {
        // 成员变量
        private Image characterImg; // 角色图片
        private Timer animationTimer; // 动画计时器
        private Timer clockTimer; // 时钟定时器
        private Timer dataRefreshTimer; // 数据刷新定时器
        private float animationOffset = 0; // 动画偏移量
        private bool animationDirection = true; // 动画方向
        private Image characterImgMouthClosed; // 嘴巴闭上的图片
        private Image characterImgMouthOpen; // 嘴巴张开的图片
        private bool isMouthOpen = false; // 跟踪嘴巴状态
        private bool isImageClicked = false; // 防止重复点击
        private Rectangle characterRect; // 记录角色图片的矩形区域

        // 模拟数据
        private int totalOrders = 0;
        private int completedOrders = 0;
        private int uncompletedOrders = 0;
        
        // 模拟历史数据 - 用于趋势图
        private List<DailyOrderData> historicalData = new List<DailyOrderData>();
        
        // 渐变色设置
        private Color pink = Color.FromArgb(255, 255, 200, 230); // 粉色
        private Color lightBlue = Color.FromArgb(255, 200, 230, 255); // 淡蓝色

        // 在LargeScreenDisplayForm类中添加以下成员变量
        private DevExpress.XtraEditors.GroupControl productionLineGroup;
        private DevExpress.XtraEditors.GroupControl productTypeGroup;
        private DevExpress.XtraEditors.GroupControl qualityGroup;
        private DevExpress.XtraCharts.ChartControl productionLineChart;
        private DevExpress.XtraCharts.ChartControl productTypeChart;
        private DevExpress.XtraCharts.ChartControl qualityChart;

        // 生产线数据
        private List<ProductionLineData> productionLineData = new List<ProductionLineData>();
        private List<ProductTypeData> productTypeData = new List<ProductTypeData>();
        private List<QualityData> qualityData = new List<QualityData>();

        public LargeScreenDisplayForm()
        {
            InitializeComponent();

            // 设置动画计时器
            animationTimer = new Timer();
            animationTimer.Interval = 30; // 30毫秒刷新一次
            animationTimer.Tick += AnimationTimer_Tick;
            
            // 设置时钟定时器，每秒更新一次时间显示
            clockTimer = new Timer();
            clockTimer.Interval = 1000; // 1秒更新一次
            clockTimer.Tick += ClockTimer_Tick;
            
            // 设置数据刷新定时器，每30秒刷新一次数据
            dataRefreshTimer = new Timer();
            dataRefreshTimer.Interval = 30000; // 30秒刷新一次
            dataRefreshTimer.Tick += DataRefreshTimer_Tick;
        }
        
        // 数据刷新定时器事件处理
        private void DataRefreshTimer_Tick(object sender, EventArgs e)
        {
            // 刷新生产订单数据
            RefreshProductionOrderData();
        }
        
        // 刷新生产订单数据
        private void RefreshProductionOrderData()
        {
            // 在实际应用中，这里应该调用后端API获取真实数据
            // 此处使用模拟数据作为示例
            
            // 模拟数据变化
            Random random = new Random();
            totalOrders = random.Next(800, 1200);
            completedOrders = random.Next(totalOrders / 2, totalOrders);
            uncompletedOrders = totalOrders - completedOrders;
            
            // 更新订单数量显示
            lblTotalOrders.Text = totalOrders.ToString();
            lblCompletedOrders.Text = completedOrders.ToString();
            lblUncompletedOrders.Text = uncompletedOrders.ToString();
            
            // 更新完成率
            int completionRate = (int)((double)completedOrders / totalOrders * 100);
            lblCompletionRate.Text = completionRate.ToString() + "%";
            
            // 更新环形图数据
            UpdateDoughnutChart();
            
            // 添加新的历史数据点
            DateTime today = DateTime.Today;
            historicalData.Add(new DailyOrderData
            {
                Date = today,
                TotalOrders = totalOrders,
                CompletedOrders = completedOrders
            });
            
            // 保持历史数据为最近7天
            if (historicalData.Count > 7)
            {
                historicalData.RemoveAt(0);
            }
            
            // 更新趋势图
            UpdateTrendChart();

            // 更新panelControl2数据和图表
            GenerateProductionData();
            UpdatePanelControl2Charts();
        }
        
        // 更新环形图
        private void UpdateDoughnutChart()
        {
            // 清除现有系列
            chartControlDoughnut.Series.Clear();
            
            // 创建新的饼图系列
            Series series = new Series("订单状态", ViewType.Doughnut);
            
            // 添加数据点
            series.Points.Add(new SeriesPoint("已完工", completedOrders));
            series.Points.Add(new SeriesPoint("未完工", uncompletedOrders));
            
            // 设置系列视图
            // 建议使用选项3，因为这样可以完全禁用爆炸效果，而不是设置一个很小的值。这样可以确保饼图的各个部分紧密连接在一起，没有间隔。
            ((DoughnutSeriesView)series.View).ExplodeMode = PieExplodeMode.None;
            ((DoughnutSeriesView)series.View).HoleRadiusPercent = 60;
            
            // 设置标签
            series.Label.TextPattern = "{A}: {V} ({VP:P0})";
            series.Label.Font = new Font("微软雅黑", 10, FontStyle.Bold);
            series.Label.TextOrientation = TextOrientation.Horizontal;
            // 不设置Position属性
            
            // 设置颜色
            series.Points[0].Color = Color.FromArgb(80, 200, 120); // 绿色 - 已完工
            series.Points[1].Color = Color.FromArgb(255, 160, 0);  // 橙色 - 未完工
            
            // 试试这个属性
            // 基础标签设置，避免使用特定位置属性
            series.Label.Visible = true;
            series.Label.TextPattern = "{A}: {V} ({VP:P0})";
            series.Label.Font = new Font("微软雅黑", 10, FontStyle.Bold);
            series.Label.TextOrientation = TextOrientation.Horizontal;

            // 可能的其他设置
            series.Label.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
            series.Label.TextAlignment = StringAlignment.Center;

            // 添加系列到图表
            chartControlDoughnut.Series.Add(series);
            
            // 禁用图例（由于我们使用标签）
            chartControlDoughnut.Legend.Visibility = DefaultBoolean.False;
        }
        
        // 更新趋势图
        private void UpdateTrendChart()
        {
            // 清除现有系列
            chartControlTrend.Series.Clear();
            
            // 创建总订单数系列
            Series totalSeries = new Series("总订单数", ViewType.Line);
            totalSeries.View.Color = Color.FromArgb(65, 140, 240); // 蓝色
            
            // 创建已完工订单系列
            Series completedSeries = new Series("已完工", ViewType.Line);
            completedSeries.View.Color = Color.FromArgb(80, 200, 120); // 绿色
            
            // 添加数据点
            foreach (var data in historicalData)
            {
                totalSeries.Points.Add(new SeriesPoint(data.Date.ToString("MM-dd"), data.TotalOrders));
                completedSeries.Points.Add(new SeriesPoint(data.Date.ToString("MM-dd"), data.CompletedOrders));
            }
            
            // 设置线条样式
            ((LineSeriesView)totalSeries.View).LineStyle.Thickness = 3;
            ((LineSeriesView)completedSeries.View).LineStyle.Thickness = 3;
            ((LineSeriesView)totalSeries.View).MarkerVisibility = DefaultBoolean.True;
            ((LineSeriesView)completedSeries.View).MarkerVisibility = DefaultBoolean.True;
            
            // 添加系列到图表
            chartControlTrend.Series.Add(totalSeries);
            chartControlTrend.Series.Add(completedSeries);
            
            // 配置X轴
            XYDiagram diagram = (XYDiagram)chartControlTrend.Diagram;
            diagram.AxisX.Label.Font = new Font("微软雅黑", 9);
            diagram.AxisX.Title.Text = "日期";
            diagram.AxisX.Title.Visibility = DefaultBoolean.True;
            
            // 配置Y轴
            diagram.AxisY.Label.Font = new Font("微软雅黑", 9);
            diagram.AxisY.Title.Text = "订单数量";
            diagram.AxisY.Title.Visibility = DefaultBoolean.True;
            
            // 启用图例
            chartControlTrend.Legend.Visibility = DefaultBoolean.True;
            chartControlTrend.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
            chartControlTrend.Legend.AlignmentVertical = LegendAlignmentVertical.Bottom;
            chartControlTrend.Legend.Direction = LegendDirection.LeftToRight;
        }
        
        // 更新时间显示
        private void ClockTimer_Tick(object sender, EventArgs e)
        {
            UpdateDateTimeDisplay();
        }
        
        // 更新日期时间显示
        private void UpdateDateTimeDisplay()
        {
            // 获取当前时间
            DateTime now = DateTime.Now;
            
            // 设置日期时间显示格式，包括年月日、时间和星期
            string dayOfWeek = "";
            switch (now.DayOfWeek)
            {
                case DayOfWeek.Monday: dayOfWeek = "星期一"; break;
                case DayOfWeek.Tuesday: dayOfWeek = "星期二"; break;
                case DayOfWeek.Wednesday: dayOfWeek = "星期三"; break;
                case DayOfWeek.Thursday: dayOfWeek = "星期四"; break;
                case DayOfWeek.Friday: dayOfWeek = "星期五"; break;
                case DayOfWeek.Saturday: dayOfWeek = "星期六"; break;
                case DayOfWeek.Sunday: dayOfWeek = "星期日"; break;
            }
            
            // 更新labelControl3的文本
            labelControl3.Text = $"{now.Year}年{now.Month}月{now.Day}日 {now.Hour:D2}:{now.Minute:D2}:{now.Second:D2} {dayOfWeek}";
        }

        private void AnimationTimer_Tick(object sender, EventArgs e)
        {
            // 简单的浮动动画效果
            if (animationDirection)
            {
                animationOffset += 0.2f;
                if (animationOffset > 5)
                    animationDirection = false;
            }
            else
            {
                animationOffset -= 0.2f;
                if (animationOffset < -5)
                    animationDirection = true;
            }

            // 重绘面板以更新动画
            panelControl1.Invalidate();
        }

        private async void LargeScreenDisplayForm_Load(object sender, EventArgs e)
        {
            // 圆形头像设置
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            int diameter = Math.Min(pictureEdit1.Width, pictureEdit1.Height);
            path.AddEllipse(0, 0, diameter, diameter);
            pictureEdit1.Region = new Region(path);

            // 加载角色图片 - 使用更可靠的方式加载透明PNG
            try
            {
                // 加载嘴巴闭上的图片
                string imgPathClosed = @"C:\Users\21413\Desktop\图片上传\生成透明 PNG 图片.png";
                // 加载嘴巴张开的图片 - 需要准备第二张图片
                string imgPathOpen = @"C:\Users\21413\Desktop\图片上传\嘴巴张开.png";

                if (File.Exists(imgPathClosed) && File.Exists(imgPathOpen))
                {
                    // 处理两张图片使其透明
                    characterImgMouthClosed = ProcessImageForTransparency(imgPathClosed);
                    characterImgMouthOpen = ProcessImageForTransparency(imgPathOpen);

                    // 默认显示嘴巴闭上的图片
                    characterImg = characterImgMouthClosed;
                }
                else
                {
                    MessageBox.Show("找不到图片文件");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载图片出错: " + ex.Message);
            }

            // 添加面板点击事件
            panelControl1.MouseClick += PanelControl1_MouseClick;

            // 启动动画
            animationTimer.Start();
            
            // 启动时钟定时器
            clockTimer.Start();
            
            // 立即更新时间显示
            UpdateDateTimeDisplay();
            
            // 获取并更新天气信息
            await UpdateWeatherInfo();
            
            // 先初始化底部面板
            InitializeBottomPanel();
            
            // 再生成历史数据
            GenerateHistoricalData();
            
            // 最后刷新数据
            RefreshProductionOrderData();
            
            // 启动定时器
            dataRefreshTimer.Start();
        }
        
        // 生成模拟历史数据
        private void GenerateHistoricalData()
        {
            historicalData.Clear();
            
            Random random = new Random();
            DateTime startDate = DateTime.Today.AddDays(-6); // 最近7天
            
            for (int i = 0; i < 7; i++)
            {
                DateTime date = startDate.AddDays(i);
                int total = random.Next(800, 1200);
                int completed = random.Next(total / 2, total);
                
                historicalData.Add(new DailyOrderData
                {
                    Date = date,
                    TotalOrders = total,
                    CompletedOrders = completed
                });
            }
        }
        
        // 获取并更新天气信息
        private async Task UpdateWeatherInfo()
        {
            try
            {
                // 这里应该调用实际的天气API
                // 由于没有真实的API，我们模拟一下天气信息
                // 实际应用中，应当替换为真实的天气API调用
                
                // 模拟的天气信息
                string weatherDesc = "今日有雨";
                string temperature = "20℃-30℃";
                
                // 更新labelControl2显示天气信息
                labelControl2.Text = $"{weatherDesc}，{temperature}";
                
                // 注意：在实际应用中，你应该使用类似以下代码来获取真实的天气数据
                /*
                using (HttpClient client = new HttpClient())
                {
                    // 替换为实际的天气API地址
                    string apiUrl = "https://api.example.com/weather?city=yourCity&key=yourApiKey";
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        // 解析JSON天气数据
                        var weatherData = JsonConvert.DeserializeObject<WeatherData>(jsonResponse);
                        
                        // 更新UI显示天气信息
                        labelControl2.Text = $"{weatherData.Weather}，{weatherData.Temperature}";
                    }
                    else
                    {
                        // 如果API调用失败，显示默认信息
                        labelControl2.Text = "今日有雨，20℃-30℃";
                    }
                }
                */
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取天气信息失败: " + ex.Message);
                // 如果获取天气失败，保留原来的显示
            }
        }

        // 处理图片透明度的方法
        private Bitmap ProcessImageForTransparency(string imagePath)
        {
            using (Bitmap originalBmp = new Bitmap(imagePath))
            {
                Bitmap transparentBmp = new Bitmap(originalBmp.Width, originalBmp.Height, PixelFormat.Format32bppArgb);

                Color cornerColor = originalBmp.GetPixel(0, 0);

                for (int y = 0; y < originalBmp.Height; y++)
                {
                    for (int x = 0; x < originalBmp.Width; x++)
                    {
                        Color pixelColor = originalBmp.GetPixel(x, y);

                        bool isBackground = Math.Abs(pixelColor.R - cornerColor.R) < 30 &&
                                          Math.Abs(pixelColor.G - cornerColor.G) < 30 &&
                                          Math.Abs(pixelColor.B - cornerColor.B) < 30;

                        transparentBmp.SetPixel(x, y, isBackground ? Color.Transparent : pixelColor);
                    }
                }

                return transparentBmp;
            }
        }

        // 鼠标点击事件处理
        private void PanelControl1_MouseClick(object sender, MouseEventArgs e)
        {
            // 检查点击是否在图片区域内
            if (characterRect.Contains(e.Location))
            {
                // 切换嘴巴状态
                isMouthOpen = !isMouthOpen;

                // 根据状态切换图片
                characterImg = isMouthOpen ? characterImgMouthOpen : characterImgMouthClosed;

                // 重绘面板以显示新图片
                panelControl1.Invalidate();
            }
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {
            // 绘制渐变背景
            using (LinearGradientBrush brush = new LinearGradientBrush(
                new Point(0, 0),
                new Point(panelControl1.Width, panelControl1.Height),
                pink,
                lightBlue))
            {
                e.Graphics.FillRectangle(brush, 0, 0, panelControl1.Width, panelControl1.Height);
            }

            // 绘制角色图像
            if (characterImg != null)
            {
                // 计算图像大小以适应面板并保持纵横比
                float ratio = Math.Min((float)panelControl1.Width / characterImg.Width,
                                      (float)panelControl1.Height / characterImg.Height);
                int width = (int)(characterImg.Width * ratio * 0.8f); // 缩小到80%以便有边距
                int height = (int)(characterImg.Height * ratio * 0.8f);

                // 计算位置，将图片靠右显示，留出20像素的边距
                int x = panelControl1.Width - width - 20;
                int y = (panelControl1.Height - height) / 2 + (int)animationOffset;

                // 记录图片区域以便检测点击
                characterRect = new Rectangle(x, y, width, height);

                // 启用高质量透明度显示
                e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
                e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                e.Graphics.SmoothingMode = SmoothingMode.HighQuality;

                // 使用支持透明度的方式绘制
                using (ImageAttributes imageAttr = new ImageAttributes())
                {
                    imageAttr.SetWrapMode(WrapMode.TileFlipXY);
                    Rectangle destRect = new Rectangle(x, y, width, height);
                    e.Graphics.DrawImage(characterImg, destRect, 0, 0, characterImg.Width, characterImg.Height, GraphicsUnit.Pixel, imageAttr);
                }
            }
        }

        // 窗体关闭时释放资源
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            animationTimer.Stop();
            clockTimer.Stop();
            dataRefreshTimer.Stop();
            if (characterImg != null)
            {
                characterImg.Dispose();
            }
            base.OnFormClosed(e);
        }

        // 在InitializeComponent调用后或在构造函数中添加初始化代码
        private void InitializePanelControl2()
        {
            // 创建TableLayoutPanel
            TableLayoutPanel layoutPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 3,
                RowCount = 1
            };
            
            layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.3F));
            layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.3F));
            layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.3F));
            
            // 创建生产线状态组
            productionLineGroup = new DevExpress.XtraEditors.GroupControl
            {
                Dock = DockStyle.Fill,
                Text = "生产线状态监控",
                AppearanceCaption = { Font = new Font("微软雅黑", 12F, FontStyle.Bold) }
            };
            
            // 创建产品类型分析组
            productTypeGroup = new DevExpress.XtraEditors.GroupControl
            {
                Dock = DockStyle.Fill,
                Text = "皮划艇型号分布",
                AppearanceCaption = { Font = new Font("微软雅黑", 12F, FontStyle.Bold) }
            };
            
            // 创建质量监控组
            qualityGroup = new DevExpress.XtraEditors.GroupControl
            {
                Dock = DockStyle.Fill,
                Text = "质量监控看板",
                AppearanceCaption = { Font = new Font("微软雅黑", 12F, FontStyle.Bold) }
            };
            
            // 创建图表控件
            productionLineChart = new DevExpress.XtraCharts.ChartControl
            {
                Dock = DockStyle.Fill
            };
            
            productTypeChart = new DevExpress.XtraCharts.ChartControl
            {
                Dock = DockStyle.Fill
            };
            
            qualityChart = new DevExpress.XtraCharts.ChartControl
            {
                Dock = DockStyle.Fill
            };
            
            // 添加图表到GroupControl
            productionLineGroup.Controls.Add(productionLineChart);
            productTypeGroup.Controls.Add(productTypeChart);
            qualityGroup.Controls.Add(qualityChart);
            
            // 添加GroupControl到布局
            layoutPanel.Controls.Add(productionLineGroup, 0, 0);
            layoutPanel.Controls.Add(productTypeGroup, 1, 0);
            layoutPanel.Controls.Add(qualityGroup, 2, 0);
            
            // 添加布局到panelControl2
            panelControl2.Controls.Add(layoutPanel);
        }

        // 在LargeScreenDisplayForm_Load中调用，生成模拟数据并初始化图表
        private void InitializeBottomPanel()
        {
            InitializePanelControl2();
            GenerateProductionData();
            UpdatePanelControl2Charts();
        }

        // 生成与panelControl3数据相关联的模拟数据
        private void GenerateProductionData()
        {
            // 清除现有数据
            productionLineData.Clear();
            productTypeData.Clear();
            qualityData.Clear();
            
            Random random = new Random();
            
            // 基于订单总数和完工数生成生产线数据
            int totalWorkload = totalOrders * 3; // 假设每个订单需要3个工序
            
            // 生成5个工序的生产线数据
            string[] stages = { "切割", "成型", "装配", "检验", "包装" };
            int remainingWork = uncompletedOrders * 3; // 未完成的工作量
            
            for (int i = 0; i < stages.Length; i++)
            {
                // 计算每个工序的完成量和剩余量，模拟工作流
                double completionFactor = 1.0 - (double)i / stages.Length; // 前面的工序完成度高
                int stageCompleted = (int)(completedOrders * 3 * completionFactor);
                int stageRemaining = Math.Min(remainingWork, (int)(uncompletedOrders * 3 * (1 - completionFactor)));
                remainingWork -= stageRemaining;
                
                // 状态：0-正常，1-待料，2-故障
                int status = i < 2 ? 0 : (random.Next(10) < 8 ? 0 : (random.Next(2) + 1));
                
                productionLineData.Add(new ProductionLineData
                {
                    StageName = stages[i],
                    Completed = stageCompleted,
                    InProgress = stageRemaining,
                    Status = status
                });
            }
            
            // 生成产品类型数据
            string[] productTypes = { "单人休闲型", "双人运动型", "专业竞技型", "家庭游乐型", "海洋探险型" };
            int totalProducts = totalOrders;
            int remainingProducts = totalProducts;
            
            for (int i = 0; i < productTypes.Length; i++)
            {
                // 为每种产品类型分配一定比例的订单
                int typeCount = (i < productTypes.Length - 1) 
                    ? (int)(totalProducts * (0.15 + random.NextDouble() * 0.15)) 
                    : remainingProducts;
                    
                remainingProducts -= typeCount;
                
                productTypeData.Add(new ProductTypeData
                {
                    ProductType = productTypes[i],
                    Count = typeCount,
                    AvgPrice = 1000 + random.Next(500, 3000) // 不同类型价格不同
                });
            }
            
            // 生成质量数据
            // 通过率基于完工率，但略有波动
            double passRate = ((double)completedOrders / totalOrders) * (0.9 + random.NextDouble() * 0.1);
            int totalInspected = completedOrders;
            int passed = (int)(totalInspected * passRate);
            int failed = totalInspected - passed;
            
            // 不同类型的缺陷
            string[] defectTypes = { "表面瑕疵", "结构问题", "尺寸偏差", "材料缺陷", "其他" };
            int remainingDefects = failed;
            
            for (int i = 0; i < defectTypes.Length; i++)
            {
                int defectCount = (i < defectTypes.Length - 1)
                    ? (int)(failed * (0.15 + random.NextDouble() * 0.2))
                    : remainingDefects;
                    
                remainingDefects -= defectCount;
                
                qualityData.Add(new QualityData
                {
                    DefectType = defectTypes[i],
                    Count = defectCount
                });
            }
        }

        // 更新panelControl2中的图表
        private void UpdatePanelControl2Charts()
        {
            // 更新生产线状态图表 - 使用堆叠条形图
            productionLineChart.Series.Clear();
            
            // 创建完成工作和在制工作的系列
            Series completedSeries = new Series("已完成", ViewType.StackedBar);
            completedSeries.View.Color = Color.FromArgb(80, 200, 120); // 绿色
            
            Series inProgressSeries = new Series("进行中", ViewType.StackedBar);
            inProgressSeries.View.Color = Color.FromArgb(65, 140, 240); // 蓝色
            
            // 创建单独的系列来表示不同状态
            Series waitingSeries = new Series("待料工序", ViewType.StackedBar);
            waitingSeries.View.Color = Color.FromArgb(255, 200, 0); // 黄色

            Series faultSeries = new Series("故障工序", ViewType.StackedBar); 
            faultSeries.View.Color = Color.FromArgb(255, 80, 80); // 红色

            // 在添加数据点时根据状态选择适当的系列
            foreach (var item in productionLineData)
            {
                completedSeries.Points.Add(new SeriesPoint(item.StageName, item.Completed));
                
                if (item.Status == 0) // 正常
                    inProgressSeries.Points.Add(new SeriesPoint(item.StageName, item.InProgress));
                else if (item.Status == 1) // 待料
                    waitingSeries.Points.Add(new SeriesPoint(item.StageName, item.InProgress));
                else if (item.Status == 2) // 故障
                    faultSeries.Points.Add(new SeriesPoint(item.StageName, item.InProgress));
            }

            // 添加所有系列到图表
            productionLineChart.Series.Add(completedSeries);
            productionLineChart.Series.Add(inProgressSeries);
            productionLineChart.Series.Add(waitingSeries);
            productionLineChart.Series.Add(faultSeries);
            
            // 配置X轴和Y轴
            XYDiagram diagram1 = (XYDiagram)productionLineChart.Diagram;
            diagram1.AxisX.Label.Font = new Font("微软雅黑", 9);
            diagram1.AxisY.Title.Text = "工作量";
            diagram1.AxisY.Title.Visibility = DefaultBoolean.True;
            
            // 启用图例
            productionLineChart.Legend.Visibility = DefaultBoolean.True;
            
            // 更新产品类型分布图表 - 使用饼图
            productTypeChart.Series.Clear();
            
            Series productTypeSeries = new Series("皮划艇型号", ViewType.Pie);
            
            foreach (var item in productTypeData)
            {
                SeriesPoint point = new SeriesPoint(item.ProductType, item.Count);
                productTypeSeries.Points.Add(point);
            }
            
            ((PieSeriesView)productTypeSeries.View).ExplodeMode = PieExplodeMode.None;
            productTypeSeries.Label.TextPattern = "{A}: {V}个 ({VP:P0})";
            productTypeSeries.Label.Font = new Font("微软雅黑", 9, FontStyle.Bold);
            
            productTypeChart.Series.Add(productTypeSeries);
            productTypeChart.Legend.Visibility = DefaultBoolean.True;
            
            // 更新质量监控图表 - 使用柱状图和指示器
            qualityChart.Series.Clear();
            
            // 添加通过率指示器
            double passRate = 1.0 - (double)qualityData.Sum(q => q.Count) / completedOrders;
            
            Series defectSeries = new Series("缺陷类型", ViewType.Bar);
            defectSeries.View.Color = Color.FromArgb(240, 128, 128); // 浅红色
            
            foreach (var item in qualityData)
            {
                defectSeries.Points.Add(new SeriesPoint(item.DefectType, item.Count));
            }
            
            qualityChart.Series.Add(defectSeries);
            
            // 添加通过率标签
            LabelControl passRateLabel = new LabelControl
            {
                Text = $"通过率: {passRate:P1}",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Dock = DockStyle.Top,
                Appearance = { TextOptions = { HAlignment = DevExpress.Utils.HorzAlignment.Center } }
            };
            
            // 颜色随通过率变化
            if (passRate >= 0.95)
                passRateLabel.Appearance.ForeColor = Color.Green;
            else if (passRate >= 0.9)
                passRateLabel.Appearance.ForeColor = Color.DarkGreen;
            else if (passRate >= 0.8)
                passRateLabel.Appearance.ForeColor = Color.Orange;
            else
                passRateLabel.Appearance.ForeColor = Color.Red;
            
            // 先清除之前的标签
            foreach (Control ctrl in qualityGroup.Controls)
            {
                if (ctrl is LabelControl && ctrl != qualityChart)
                    qualityGroup.Controls.Remove(ctrl);
            }
            
            qualityGroup.Controls.Add(passRateLabel);
            
            // 配置X轴和Y轴
            XYDiagram diagram3 = (XYDiagram)qualityChart.Diagram;
            diagram3.AxisX.Label.Font = new Font("微软雅黑", 8);
            diagram3.AxisY.Title.Text = "缺陷数量";
            
            qualityChart.Legend.Visibility = DefaultBoolean.False;
        }

        // 添加数据类
        public class ProductionLineData
        {
            public string StageName { get; set; }
            public int Completed { get; set; }
            public int InProgress { get; set; }
            public int Status { get; set; } // 0-正常，1-待料，2-故障
        }

        public class ProductTypeData
        {
            public string ProductType { get; set; }
            public int Count { get; set; }
            public double AvgPrice { get; set; }
        }

        public class QualityData
        {
            public string DefectType { get; set; }
            public int Count { get; set; }
        }
    }
    
    // 日订单数据类
    public class DailyOrderData
    {
        public DateTime Date { get; set; }
        public int TotalOrders { get; set; }
        public int CompletedOrders { get; set; }
    }
}